package sandbox.service;

import java.util.Calendar;
import java.util.List;

import org.slim3.datastore.Datastore;
import org.slim3.datastore.InMemoryFilterCriterion;
import org.slim3.datastore.ModelQuery;

import sandbox.meta.SampleInfoMeta;
import sandbox.model.SampleInfo;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.SortDirection;

public class SampleService {

    private SampleService() {
    }

    public static List<SampleInfo> getSamplesBySite(final Key... keys) {
        Calendar to = Calendar.getInstance();
        to.add(Calendar.WEEK_OF_MONTH, -1);

        ModelQuery<SampleInfo> query = Datastore
            .query(SampleInfoMeta.get())
            .filter("timestamp", FilterOperator.GREATER_THAN_OR_EQUAL, to.getTime());
        if (keys != null && keys.length > 0 && keys[0] != null) {
            query.filterInMemory(new InMemoryFilterCriterion() {
                public boolean accept(Object model) {
                    return SampleInfo.class.cast(model).getSiteKey().equals(keys[0]);
                }
            });
        }
        query = query.sort("timestamp", SortDirection.DESCENDING);
        return query.asList();
    }

    public static SampleInfo getSample(Key key) {
        return Datastore.get(SampleInfoMeta.get(), key);
    }

}
